package com.xiamo.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiamo.common.AjaxResult;
import com.xiamo.entity.Message;
import com.xiamo.service.IMessageService;
import com.xiamo.utils.ws.SimpleWebsocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description:  留言
 * @return:
 * @Author: dawu
 * @Date: 2024-04-09 10:02
 */
@RestController
@RequestMapping("message")
public class MessageController {
    @Autowired
    private IMessageService messageService;
    @Resource
    private SimpleWebsocketServer simpleWebsocketServer;
    @GetMapping("list")
    public AjaxResult list(@RequestParam(defaultValue = "1") Integer page){

        Page<Message> pageObj = new Page<>(page, 10);
        messageService.page(pageObj, Wrappers.<Message>lambdaQuery().orderByDesc(Message::getCreateTime));
        List<Message> messages = pageObj.getRecords();

        simpleWebsocketServer.sendMessagesToAll(messages);
        return AjaxResult.success(pageObj);
    }


    @PostMapping("create")
    public AjaxResult create(@RequestBody Message message){

        return AjaxResult.success(messageService.save(message));
    }
    @DeleteMapping("delete")
    public AjaxResult delete(@RequestBody Message message){

        return AjaxResult.success(messageService.removeById(message.getMessageId()));
    }
}
